require('dotenv').config();
const express = require('express');
const bodyParser = require('body-parser');
const { sequelize } = require('./models');
const debugRoutes = require('./routes/debug');
const userRoutes = require('./routes/users');
const healthRoutes = require('./routes/health');

const app = express();
app.use(bodyParser.json());

app.use('/api/health', healthRoutes);
app.use('/api/debug', debugRoutes);
app.use('/api/users', userRoutes);

const PORT = process.env.PORT || 3503;

async function startServer() {
  try {
    await sequelize.authenticate();
    console.log('数据库连接成功');

    if (process.env.DB_SYNC === 'true') {
      await sequelize.sync({ alter: true });
      console.log('数据库模型同步完成 (DB_SYNC=true)');
    } else {
      console.log('跳过自动同步（DB_SYNC !== "true"）');
    }

    app.listen(PORT, () => {
      console.log(`服务器运行在端口 ${PORT}`);
    });
  } catch (err) {
    console.error('启动失败：', err);
    process.exit(1);
  }
}

startServer();
module.exports = app;